#!/bin/sh
set -o nounset
#set -x #DEBUG

. bin/library.sh

PLAINTEXT=$ISOMNT_RW/casper/filesystem.squashfs
MAPPERFILE=squashfs
LOOPFILE=$PLAINTEXT.luks

# Exit if not configured
if [ "${CONFIG_ENCRYPT_ROOTFS-x}" != "y" ] ; then exit 0; fi

# Exit if LUKS file exists and plaintext is a symlink
if [ -f $LOOPFILE ] && [ -h $PLAINTEXT ] ; then exit 0; fi

require_iso_rw_mounted

# Overhead in block size for luks header (512 byte blocks)
LUKSBLOCKS=4096

[ -f $PLAINTEXT ] || die Root filesystem squashfs file not found!

# Measure the size of the plaintext file
NBLOCKS=`ls -l --block-size=512 $PLAINTEXT | cut -f 5 -d ' '`
LOOPBLOCKS=$(($LUKSBLOCKS+$NBLOCKS))
printinfo Creating $LOOPFILE from root filesystem squashfs:
printinfo Plaintext file is $NBLOCKS blocks \(512 bytes each\)
printinfo Creating zeroed LUKS container file of $LOOPBLOCKS blocks, using $LUKSBLOCKS blocks as overhead...

# Create a zeroed container file
$SUDO rm -f $LOOPFILE &&
$SUDO dd if=/dev/zero of=$LOOPFILE bs=512 count=$LOOPBLOCKS >/dev/null 2>&1 || die Unable to create LUKS container file!

# Find an available loop device
LOOPDEV=`$SUDO losetup -f` || die Unable to find available loop device!
printinfo Using available loop device $LOOPDEV

# Map container file to loop device
$SUDO losetup $LOOPDEV $LOOPFILE || die Unable to mount LUKS container onto loop device!

release_and_die () {
    $SUDO losetup -d $1
    shift
    die $@
}

# Create encrypted luks format
printinfo Formatting encrypted device...
$SUDO cryptsetup luksFormat $LOOPDEV || release_and_die $LOOPDEV Unable to format encrypted device!

# Mount encrypted file
printinfo Opening encrypted device...
$SUDO cryptsetup luksOpen $LOOPDEV $MAPPERFILE || release_and_die $LOOPDEV Unable to mount encrypted device!

# Copy plaintext into encrypted device
printinfo Copying plaintext file into encrypted device...
$SUDO dd if=$PLAINTEXT of=/dev/mapper/$MAPPERFILE bs=512 count=$NBLOCKS || release_and_die $LOOPDEV Unable to copy plaintext into encrypted container!

# Unmount encrypted drive
printinfo Unmounting encrypted device...
$SUDO cryptsetup luksClose /dev/mapper/$MAPPERFILE || release_and_die $LOOPDEV Unable to unmount encrypted device!

# Unmount loop device
printinfo Releasing loop file $LOOPDEV
$SUDO losetup -d $LOOPDEV || die Unable to release loop device!

# Remove plaintext file
# Create symlink to spoof plaintext file
$SUDO rm -f $PLAINTEXT &&
$SUDO ln -sf /dev/mapper/$MAPPERFILE $PLAINTEXT || die Unable to spoof plaintext file!

# Indicate ISO RW filesystem modified
touch stamps/isofs.stamp

exit 0
